package jdk8_functional_interface;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author 07509-Chang Shengwei
 * @version Id: FunctionalInterfaceTest.java, v 0.1 2021/5/29 11:58 Chang Shengwei Exp $
 * @description
 */
public class FunctionalInterfaceTest {

    public static void main(String[] args) {
        FunctionalInterfaceTest functionalInterfaceTest = new FunctionalInterfaceTest();
        // 测试消费型接口
        functionalInterfaceTest.testConsumerInterface();

        // 测试供应型接口
        functionalInterfaceTest.testSupplierInterface();

        // 测试函数型接口
        functionalInterfaceTest.testFunctionalInterface();

        // 测试断言型接口
        functionalInterfaceTest.testPredicateInterface();

    }


    /**
     * 消费型接口 accept()方法，Performs this operation on the given argument.
     * @param money
     * @param con
     */
    public void happy(double money, Consumer<Double> con){
        con.accept(money);
    }

    public void testConsumerInterface(){
        happy(100000, System.out::println);
    }


    /**
     * 供应型接口 get()方法，Gets a result.
     * @param num
     * @param sup
     * @return
     */
    public List<Integer> getNumList(int num, Supplier<Integer> sup){
        List<Integer> list = new ArrayList<>();

        for(int i = 0; i < num; i++){
            Integer n = sup.get();
            list.add(n);
        }

        return list;
    }

    public void testSupplierInterface(){
        List<Integer> list = getNumList(10, () -> (int) (Math.random() * 100));

        list.forEach(x -> System.out.println(x));
    }


    /**
     * 函数型接口 apply()方法，Applies this function to the given argument.
     * @param str
     * @param fun
     * @return
     */
    public String strHandler(String str, Function<String, String> fun){
        return fun.apply(str);
    }

    public void testFunctionalInterface(){
        System.out.println(strHandler("---------", s -> s.substring(2, 6)));
    }


    /**
     * 断言型接口 test()方法，Evaluates this predicate on the given argument.
     * @param list
     * @param pre
     * @return
     */
    public List<String> filterStr(List<String> list, Predicate<String> pre){
        List<String> strList = new LinkedList<>();

        list.forEach(x -> {
            if (pre.test(x)){
                strList.add(x);
            }
        });

        return strList;
    }

    public void testPredicateInterface(){
        List<String> strList = filterStr(Arrays.asList("hello","python","wa","lambda"), s -> s.length() > 5);
        strList.forEach(x -> System.out.println(x));
    }
}
